package cn.org.wifit.core.zookeeper.manager;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;

import cn.org.wifit.core.zookeeper.watcher.ServerBootWatcher;

/**
 * 这个管理器主要是在某个服务器启动时使用。
 * 当几个服务器器同事启动时，为了保证至多个服务器中本地ServerTreeNode节点的记录都是完整、统一的。
 * 所以要使用zookeeper的分布式事务锁，让每台服务器依次启动
 * @author wenjie
 */
public class ZookeeperServerBootWriteManager {
	/**
	 * 由spring托管的一个单例对象
	 */
	private ZooKeeper zk;
	
	/**
	 * 这个watcher专门用于监控IMUser节点以及其子节点的变化
	 */
	private ServerBootWatcher serverBootWatcher;

	/**
	 * 同步等待启动
	 */
	public void syncBoot() {
		try {
			//注册监听
			this.zk.getChildren("/Boot", this.serverBootWatcher);
			//向/Boot注册自己的分布式事务锁节点
			String mypath = this.zk.create("/Boot/ServerBoot", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
			String mySequence = mypath.substring(mypath.length()-10, mypath.length());
			this.serverBootWatcher.setMySequence(mySequence);
			synchronized (this.serverBootWatcher) {
				this.serverBootWatcher.notify();
			}
			
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
	
	public ZooKeeper getZk() {
		return zk;
	}

	public void setZk(ZooKeeper zk) {
		this.zk = zk;
	}

	public ServerBootWatcher getServerBootWatcher() {
		return serverBootWatcher;
	}

	public void setServerBootWatcher(ServerBootWatcher serverBootWatcher) {
		this.serverBootWatcher = serverBootWatcher;
	}
}